package com.ycshihuo.shihuo.util;

import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.math.BigInteger;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;

/**
 * 密码工具类
 * Created by Zack on 16/5/11.
 */
public class PasswordUtil {

    private static final String PBKDF2_ALGORITHM = "PBKDF2WithHmacSHA1";

    private static final int SALT_BYTE_SIZE = 24;
    private static final int HASH_BYTE_SIZE = 24;
    private static final int PBKDF2_ITERATIONS = 1000;

    private static final int SALT_INDEX = 0;
    private static final int PBKDF2_INDEX = 1;

    /**
     * 返回经过PBKDF2加盐的密码
     *
     * @param password 需要hash的密码
     * @return 经过加盐hash的密码
     */
    public static String createHash(String password)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        return createHash(password.toCharArray());
    }

    /**
     * 返回经过PBKDF2加盐的密码
     *
     * @param password 需要hash的密码
     * @return 经过加盐hash的密码
     */
    public static String createHash(char[] password)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        // 生成随机盐
        SecureRandom random = new SecureRandom();
        byte[] salt = new byte[SALT_BYTE_SIZE];
        random.nextBytes(salt);

        // hash密码
        byte[] hash = pbkdf2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
        // 格式 iterations:salt:hash
        return toHex(salt) + ":" + toHex(hash);
    }

    /**
     * 验证密码与hash是否匹配
     *
     * @param password    需要验证的密码
     * @param correctHash 正确的密码hash值
     * @return 验证结果
     */
    public static boolean validatePassword(String password, String correctHash)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        return validatePassword(password.toCharArray(), correctHash);
    }

    /**
     * 验证密码与hash是否匹配
     *
     * @param password    需要验证的密码
     * @param correctHash 正确的密码hash值
     * @return 验证结果
     */
    public static boolean validatePassword(char[] password, String correctHash)
            throws NoSuchAlgorithmException, InvalidKeySpecException {

        String[] params = correctHash.split(":");
        int iterations = PBKDF2_ITERATIONS;
        byte[] salt = fromHex(params[SALT_INDEX]);
        byte[] hash = fromHex(params[PBKDF2_INDEX]);
        // 使用给定的密码, 计算使用相同的盐/迭代次数/hash长度得到的hash
        byte[] testHash = pbkdf2(password, salt, iterations, hash.length);
        // 对比hash值,使用定长时间
        return slowEquals(hash, testHash);
    }

    /**
     * 使用恒定时间对比算法进行计算
     * 此算法按位进行异或计算, 可有效避免时序攻击
     *
     * @param a 字符数组a
     * @param b 字符数组b
     * @return 对比结果
     */
    private static boolean slowEquals(byte[] a, byte[] b) {
        int diff = a.length ^ b.length;
        for (int i = 0; i < a.length && i < b.length; i++)
            diff |= a[i] ^ b[i];
        return diff == 0;
    }

    /**
     * 计算指定密码的 PBKDF2 hash
     *
     * @param password   需要hash的密码
     * @param salt       盐值
     * @param iterations 迭代次数
     * @param bytes      hash位数
     * @return hash结果
     */
    private static byte[] pbkdf2(char[] password, byte[] salt, int iterations, int bytes)
            throws NoSuchAlgorithmException, InvalidKeySpecException {
        PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, bytes * 8);
        SecretKeyFactory skf = SecretKeyFactory.getInstance(PBKDF2_ALGORITHM);
        return skf.generateSecret(spec).getEncoded();
    }

    /**
     * 转换16进制字符串为字节数组
     *
     * @param hex 16进制字符串
     * @return 字节数组
     */
    private static byte[] fromHex(String hex) {
        byte[] binary = new byte[hex.length() / 2];
        for (int i = 0; i < binary.length; i++) {
            binary[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2), 16);
        }
        return binary;
    }

    /**
     * 转换字节数组为16进制字符串
     *
     * @param array 需要转换的字节数组
     * @return 长度*2的字符串
     */
    private static String toHex(byte[] array) {
        BigInteger bi = new BigInteger(1, array);
        String hex = bi.toString(16);
        int paddingLength = (array.length * 2) - hex.length();
        if (paddingLength > 0)
            return String.format("%0" + paddingLength + "d", 0) + hex;
        else
            return hex;
    }

}
